const router = require('koa-router')()
const mysql = require('../database/database');


router.get('/cha', async (ctx, next) => {
  const statement = 'select * from todolist',
    result = await mysql.execute(statement);

  ctx.body = JSON.stringify(result[0]);
  // ctx.body = 'koa2 string'
  // await ctx.render('index', {
  //   title: 'Hello Koa 2!'
  // })
})

router.post('/delete', async (ctx, next) => {

  const statement = 'delete from todolist where id = ?;',
    params = ctx.request.body.item,
    result = await mysql.execute(statement, [params.id]);

  console.log(result[0]);
  ctx.body = 'koa2 string'
})

router.post('/addItem', async (ctx, next) => {
  // console.log(typeof ctx.request.body);
  // console.log(ctx.request.body);
  const params = ctx.request.body.item,
    statement = 'insert into todolist (id, content, completed) values(?, ?, ?)',
    result = await mysql.execute(statement, [params.id, params.content, params.completed]);

  console.log(result[0]);
  ctx.body = {
    title: 'koa2 json'
  }
})

router.post('/updateItem', async (ctx, next) => {
  console.log(typeof ctx.request.body);
  console.log(ctx.request.body);
  const params = ctx.request.body.item,
    statement = 'update contents set content = ?, completed = ? where id = ?',
    result = await mysql.execute(statement, [params.content, params.completed ? 1 : 0, params.id]);

  console.log(result[0]);
  ctx.body = {
    title: 'koa2 json'
  }
})

module.exports = router
